package com.woniuxy.house.mapper;

import com.woniuxy.house.entity.Message;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
 * 针对聊天信息表提供的mapper接口
 */
public interface MessageMapper {
	/**
	 * 增加信息
	 *
	 * @param message 实体类
	 */
	@Insert("insert into house_message(content,time,user_id,opp_user_id,status)values(#{content},#{time},#{sender.id},#{receiver.id},#{status})")
	void add(Message message);

	/**
	 * 删除消息 根据id
	 *
	 * @param id
	 */
	@Delete("delete from house_message where id=#{id}")
	void delete(Integer id);

	/**
	 * 根据用户id 删除消息 （这里有可能是多条消息）
	 *
	 * @param id
	 */
	@Delete("delete from house_message where user_id=#{id}")
	void deleteByUser(Integer id);

	/**
	 * 根据用户id 查询消息 并且把发送者 接收者用户的详情都带出来(这里只是user_id的情况 还有opp_user_id的情况)
	 *
	 * @param id
	 * @return message 类型的list 集合
	 */
	@Select("SELECT m.* FROM house_message m, house_user u WHERE m.user_id=u.id AND (m.user_id=#{id} OR m.opp_user_id=#{id})")
	@ResultMap("MessageMap")
	List<Message> getByUserId(Integer id);

	/**
	 * 根据发送者id和接收者id 查询两个用户之间的全部聊天消息
	 */
	@Select("SELECT * FROM house_message  WHERE user_id IN(#{senderId},#{receiverId}) AND opp_user_id IN(#{senderId},#{receiverId})")
	List<Message> getAll(@Param("senderId") int senderId, @Param("receiverId") int receiverId);

	/**
	 * 根据id查询消息
	 *
	 * @param id
	 * @return message类 (并带出用户信息)
	 */
	@Select("select m.* from house_message m, house_user u where m.user_id=u.id and m.id=#{id}")
	@Results(id = "MessageMap",value = {
			@Result(column = "id", property = "id", id = true),
			@Result(column = "content", property = "content"),
			@Result(column = "time", property = "time"),
			@Result(column = "status", property = "status"),
			@Result(column = "user_id", property = "sender", one = @One(select = "com.woniuxy.house.mapper.UserMapper.getById", fetchType = FetchType.LAZY)),
			@Result(column = "opp_user_id", property = "receiver", one = @One(select = "com.woniuxy.house.mapper.UserMapper.getById", fetchType = FetchType.LAZY)),

	})
	Message getById(Integer id);

	/**
	 * 查询聊天记录
	 *
	 * @param uid
	 * @param oid
	 * @return
	 */
	@Select("SELECT * FROM house_message WHERE user_id=#{uid} and opp_user_id=#{oid} or user_id=#{oid} and opp_user_id=#{uid} ORDER BY TIME ")
	@ResultMap("MessageMap")
	List<Message> getByUserIdAndOtherId(@Param("uid") Integer uid, @Param("oid") Integer oid);
	@Select("SELECT * FROM house_message WHERE user_id=#{uid} OR opp_user_id=#{uid} ")
	@ResultMap("MessageMap")
	List<Message> getMsgListByUserId(Integer uid);
	@Update("update house_message set status='2' where user_id=#{oid} and opp_user_id=#{uid} ")
	void updateMessageStatus(@Param("uid") Integer uid, @Param("oid") Integer oid);
}
